package robust.gradle.plugin

import com.meituan.robust.Constants
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.logging.Logger

/**
 * 插件的入口类
 */
class RobustPlugin implements Plugin<Project> {

    def robust

    /**
     * 是否强制插入插入代码，Robust默认在debug模式下是关闭的，开启这个选项为true会在debug下插入代码
     */
    private static boolean isForceInsert = false

    static Logger logger

    @Override
    void apply(Project project) {

        //解析robust.xml文件
        robust = new XmlSlurper().parse(new File("${project.projectDir}/${Constants.ROBUST_XML}"))
        logger = project.logger

        //是否是强制插入，true debug环境也进行方法插入
        if (robust.switch.forceInsert != null && "true" == String.valueOf(robust.switch.forceInsert.text()))
            isForceInsert = true
        else
            isForceInsert = false

        isForceInsert=true
        logger.quiet("isForceInsert -> isForceInsert")

        //isForceInsert 是true的话，则强制执行插入，false不进行插桩
        if (isForceInsert) {
            //注册方法1
            project.android.registerTransform(new RobustTransform(project))
            //注册方式2
//            project.extensions.getByType(BaseExtension.class).registerTransform(new RobustTransform(project))
            project.afterEvaluate(new RobustApkHashAction())
            return
        }

        /** isForceInsert false 需要进行任务的判断，debug任务不进行插桩 **/

        //获取任务名称
        def taskNames = project.gradle.startParameter.taskNames
        //是否是debug任务，默认值为false
        def isDebugTask = false
        for (index in 0..<taskNames.size()) {
            def taskName = taskNames[index]
            //任务名称中含有Debug,就认为是Debug环境
            if (taskName.endsWith("Debug") || taskName.contains("Debug")){
                isDebugTask=true
                break
            }
        }
        logger.quiet("isDebugTask -> $isDebugTask")

        //不是debug环境，进行注册
        if (!isDebugTask){
            project.android.registerTransform(new RobustTransform(project))
//            project.extensions.getByType(BaseExtension.class).registerTransform(new RobustTransform(project))
            project.afterEvaluate(new RobustApkHashAction())
            logger.quiet "Register robust transform successful !!!"
        }

        //这个暂时没有用
        if (null != robust.switch.turnOnRobust && "true" != String.valueOf(robust.switch.turnOnRobust)) {
            return
        }
    }
}